/*jslint browser: true*/
/*global $, jQuery, alert, window*/
function get_today() {
    "use strict";
    var today = new Date(),
        data_list = [],
        month = today.getMonth() + 1,
        day = today.getDate();
    if (month < 10) {
        month = "0" +  month;
    }
    if (day < 10) {
        day = "0" +  day;
    }
    data_list.push(today.getFullYear());
    data_list.push(month);
    data_list.push(day);
    return data_list.join("/");
}

function hide_elemet_by_id(id_dict) {
    "use strict";
    var id_name;
    for (id_name in id_dict) {
        if (id_dict.hasOwnProperty(id_name) && id_dict[id_name] === 0) {
            $("#" + id_name).hide();
        }
    }
}
function hide_elemet_by_class(class_dict) {
    "use strict";
    var class_name;
    for (class_name in class_dict) {
        if (class_dict.hasOwnProperty(class_name) && class_dict[class_name] === 0) {
            $("." + class_name).hide();
        }
    }
}

window.view = {};
window.view.set = {
    "paper_title": function (str_value) {
        "use strict";
        $("#paper_title").html(str_value);
    },
    "full_mark": function (str_value) {
        "use strict";
        $("#full_mark").html(str_value);
    },
    "pass_score": function (str_value) {
        "use strict";
        $("#pass_score").html(str_value);
    },
    "date": function (str_value) {
        "use strict";
        $("#date").html(str_value);
    },
    "time_limit": function (str_value) {
        "use strict";
        $("#time_limit").html(str_value);
    },
    "time_rest": function (str_value) {
        "use strict";
        $("#time_rest").html(str_value);
    }
};
window.sync = {
    "paper_data_html": function () {
        "use strict";
        var paper_data = window.format.s2c(window.storage(window.paper_key),
                                           window.format.paper)[0],
            exam_data = window.format.s2c(window.storage(window.exam_key),
                                           window.format.exam)[0];
        window.view.set.paper_title(paper_data.name);
        window.view.set.full_mark(paper_data.score);
        window.view.set.pass_score(paper_data.pass_score);
        window.view.set.time_limit(paper_data.time_limit);
        if (window.page_his) {
            window.view.set.date(window.int_to_date(exam_data.date));
            $("#submit_answer").hide();
        } else {
            window.view.set.date(get_today());
            window.view.set.time_rest(paper_data.time_limit);
            $("#close_paper").hide();
        }
        if (window.is_train) {
            $(".is_train").hide();
            $("#category_name").html("强化训练");
        }
    },
    "question_data_html": function () {
        "use strict";
        var detail = window.format.s2c(window.storage(window.detail_key),
                                       window.format.detail)[0],
            desp_dict = window.desp_dict,
            hat_dict = detail.hat,
            question_list = detail.question,
            answer_dict = detail.answer || {},
            index = 0,
            length = question_list.length,
            item,
            saved_type,
            saved_hat = 0,
            table_id,
            table_str = '<h5 class="teste_title" id="{type}_title">{detail}</h5>' +
                '<table class="test_detail" id="{type}_detail"></table>',
            image_str = '<p><a target="_blank" href="/link/{id}/image/">图片链接</a></p>',
            hat_data;
        while (index < length) {
            item = question_list[index];
            /*{id:1, hat:0, type:"", body:, img:, opt:, len:, score:,},
              {id:2, hat:2, type:"", body:, img:, opt:, len:, score:,},*/
            saved_type = item.type;
            table_id = "#{type}_detail".format({type: item.type});
            $(table_str.format({
                type: item.type,
                detail: desp_dict[item.type]
            })).appendTo("#detail_container");
            while (index < length) {
                item = question_list[index];
                if (item.type !== saved_type) {
                    break;
                }
                //hat
                if (item.hat !== 0 && item.hat !== saved_hat) {
                    saved_hat = item.hat;
                    hat_data = hat_dict[item.hat];
                    /*hat: {"1": {body:, img:,},
                            "2": {body:, img:,}, }*/
                    $('<tr><td colspan="2">{body}{image}</td></tr>'.format({
                        body: hat_data.body,
                        image: hat_data.img ? image_str.format({id: hat_data.img}) : ""
                    })).appendTo(table_id);
                }
                $('<tr><td class="body">' +
                    '{body}{image}<p>{options}</p><p>（{score}分）</p>'.format({
                        body: item.body,
                        image: item.img ? image_str.format({id: item.img}) : "",
                        options: item.opt,
                        score: item.score
                    }) +
                    '</td><td>{count}</td></tr>'.format({
                        count: window.get_answer_radio(item.id, item.len)
                    })).appendTo(table_id);
                //loop
                index += 1;
            }
        }
        $('<div class="space"></div>').appendTo("#detail_container");
    },
    "analysis_data_html": function () {
        "use strict";
        var exam_detail = window.format.s2c(window.storage(window.exam_key),
                                            window.format.exam)[0],
            your_answer = exam_detail.answer,
            detail = window.format.s2c(window.storage(window.detail_key),
                                       window.format.detail)[0],
            desp_dict = window.desp_dict,
            hat_dict = detail.hat,
            question_list = detail.question,
            answer_dict = detail.answer || {},
            index = 0,
            length = question_list.length,
            question_item,
            correct_answer_item,
            saved_type,
            saved_hat = 0,
            table_id,
            table_str = '<h5 class="teste_title" id="{type}_title">{detail}</h5>' +
                '<table class="test_detail" id="{type}_detail"></table>',
            image_str = '<p><a target="_blank" href="/link/{id}/image/">图片链接</a></p>',
            tr_list = [],
            hat_data;
        while (index < length) {
            question_item = question_list[index];
            /*{id:1, hat:0, type:"", body:, img:, opt:, len:, score:,},
              {id:2, hat:2, type:"", body:, img:, opt:, len:, score:,},*/
            saved_type = question_item.type;
            table_id = "#{type}_detail".format({type: question_item.type});
            $(table_str.format({
                type: question_item.type,
                detail: desp_dict[question_item.type]
            })).appendTo("#detail_container");
            while (index < length) {
                question_item = question_list[index];
                correct_answer_item = answer_dict[question_item.id];
                if (question_item.type !== saved_type) {
                    break;
                }
                //hat
                if (question_item.hat !== 0 && question_item.hat !== saved_hat) {
                    saved_hat = question_item.hat;
                    hat_data = hat_dict[question_item.hat];
                    /*hat: {"1": {body:, img:,},
                            "2": {body:, img:,}, }*/
                    tr_list.push('<tr><td colspan="2">{body}{image}</td></tr>'.format({
                        body: hat_data.body,
                        image: hat_data.img ? image_str.format({id: hat_data.img}) : ""
                    }));
                }
                //question boday
                tr_list.push('<tr>');
                tr_list.push('<td class="body">{body}{image}<p>{options}</p><p>（{score}分）</p></td>'.format({
                    body: question_item.body,
                    image: question_item.img ? image_str.format({id: question_item.img}) : "",
                    options: question_item.opt,
                    score: question_item.score
                }));
                tr_list.push('<td><p class="sub_correct">{correct}</p>'.format({
                    correct: correct_answer_item.answer
                }));
				tr_list.push('<p class="sub_answer">{answer}</p></td>'.format({
                    answer: your_answer[question_item.id]
                }));
                tr_list.push('</tr>');
                //analysis and answer
                tr_list.push('<tr>');
				tr_list.push('<td class="sub_analyze">{analysis}</td>'.format({
                    analysis: correct_answer_item.analysis
                }));
                if (correct_answer_item.answer === your_answer[question_item.id]) {
                    tr_list.push('<td><p class="sub_score">{score}</p>'.format({
                        score: question_item.score
                    }));
                    tr_list.push('<div class="{correct}"></div></td>'.format({
                        correct: "correct"
                    }));
                } else {
                    tr_list.push('<td><p class="sub_score">{score}</p>'.format({
                        score: 0
                    }));
                    tr_list.push('<div class="{correct}"></div></td>'.format({
                        correct: "wrong"
                    }));
                }
                tr_list.push('</tr>');
                //loop
                $(tr_list.join("")).appendTo(table_id);
                tr_list = [];
                index += 1;
            }
        }
        $('<div class="space"></div>').appendTo("#detail_container");
    },
    "incorrect_data_html": function () {
        "use strict";
        var exam_detail = window.format.s2c(window.storage(window.exam_key),
                                            window.format.exam)[0],
            your_answer = exam_detail.answer,
            detail = window.format.s2c(window.storage(window.detail_key),
                                       window.format.detail)[0],
            desp_dict = window.desp_dict,
            hat_dict = detail.hat,
            question_list = detail.question,
            answer_dict = detail.answer || {},
            index = 0,
            length = question_list.length,
            question_item,
            correct_answer_item,
            saved_type,
            saved_hat = 0,
            table_id,
            table_str = '<h5 class="teste_title" id="{type}_title">{detail}</h5>' +
                '<table class="test_detail" id="{type}_detail"></table>',
            image_str = '<p><a target="_blank" href="/link/{id}/image/">图片链接</a></p>',
            tr_list = [],
            display_talbe_id = {},
            display_hat_class = {},
            hat_data;
        while (index < length) {
            question_item = question_list[index];
            /*{id:1, hat:0, type:"", body:, img:, opt:, len:, score:,},
              {id:2, hat:2, type:"", body:, img:, opt:, len:, score:,},*/
            saved_type = question_item.type;
            display_talbe_id[question_item.type + "_title"] = 0;
            display_talbe_id[question_item.type + "_detail"] = 0;
            table_id = "#{type}_detail".format({type: question_item.type});
            $(table_str.format({
                type: question_item.type,
                detail: desp_dict[question_item.type]
            })).appendTo("#detail_container");
            while (index < length) {
                question_item = question_list[index];
                correct_answer_item = answer_dict[question_item.id];
                if (question_item.type !== saved_type) {
                    break;
                }
                //hat
                if (question_item.hat !== 0 && question_item.hat !== saved_hat) {
                    saved_hat = question_item.hat;
                    display_hat_class["hat_" +  question_item.hat] = 0;
                    hat_data = hat_dict[question_item.hat];
                    /*hat: {"1": {body:, img:,},
                            "2": {body:, img:,}, }*/
                    tr_list.push('<tr class="hat_{hat_id}"><td colspan="2">{body}{image}</td></tr>'.format({
                        hat_id: saved_hat,
                        body: hat_data.body,
                        image: hat_data.img ? image_str.format({id: hat_data.img}) : ""
                    }));
                }
                //question boday
                if (correct_answer_item.answer !== your_answer[question_item.id]) {
                    tr_list.push('<tr class="hat_{hat_id}">'.format({hat_id: saved_hat}));
                    tr_list.push('<td class="body">{body}{image}<p>{options}</p><p>（{score}分）</p></td>'.format({
                        body: question_item.body,
                        image: question_item.img ? image_str.format({id: question_item.img}) : "",
                        options: question_item.opt,
                        score: question_item.score
                    }));
                    tr_list.push('<td><p class="sub_correct">{correct}</p>'.format({
                        correct: correct_answer_item.answer
                    }));
                    tr_list.push('<p class="sub_answer">{answer}</p></td>'.format({
                        answer: your_answer[question_item.id]
                    }));
                    tr_list.push('</tr>');
                    //analysis and answer
                    tr_list.push('<tr class="hat_{hat_id}">'.format({hat_id: saved_hat}));
                    tr_list.push('<td class="sub_analyze">{analysis}</td>'.format({
                        analysis: correct_answer_item.analysis
                    }));
                    tr_list.push('<td><p class="sub_score">{score}</p>'.format({
                        score: 0
                    }));
                    tr_list.push('<div class="{correct}"></div></td>'.format({
                        correct: "wrong"
                    }));
                    display_talbe_id[question_item.type + "_title"] += 1;
                    display_talbe_id[question_item.type + "_detail"] += 1;
                    display_hat_class["hat_" +  question_item.hat] += 1;
                    tr_list.push('</tr>');
                }
                //loop
                $(tr_list.join("")).appendTo(table_id);
                tr_list = [];
                index += 1;
            }
        }
        hide_elemet_by_id(display_talbe_id);
        hide_elemet_by_class(display_hat_class);
        $('<div class="space"></div>').appendTo("#detail_container");
    }
};
window.init = {
    "global_var": function () {
        "use strict";
        var pathname = location.pathname,
            exam_reg = new RegExp('^/exam/([0-9]+)/exam/$'),
            history_reg = new RegExp('^/exam/([0-9]+)/(analysis|incorrect)/$'),
            exam_result = exam_reg.exec(pathname),
            exam_data;
        exam_result = exam_result || history_reg.exec(pathname);
        if (exam_result) {
            window.is_valid = true;
            window.is_exam = true;
            window.exam_id = parseInt(exam_result[1], 10);
            window.exam_key = "/exam/{id}/".format({id: window.exam_id});
            exam_data = window.format.s2c(window.storage(window.exam_key),
                                           window.format.exam)[0];
            window.paper_id = exam_data.paper_id;
            window.paper_key = "/paper/{id}/".format({id: exam_data.paper_id});
            window.detail_key = "/paper/detail/{id}/".format({id: exam_data.detail_id});
            window.is_train = (exam_data.category_num === 1);
            window.page_his = exam_result[2] || false;
        }
    },
    "paper_data": function () {
        "use strict";
        window.sync.paper_data_html();
    },
    "question_data": function () {
        "use strict";
        switch (window.page_his) {
        case "analysis":
            window.sync.analysis_data_html();
            break;
        case "incorrect":
            window.sync.incorrect_data_html();
            break;
        default:
            window.sync.question_data_html();
        }
        
    },
    "start_watch": function () {
        "use strict";
        var exam_data = window.format.s2c(window.storage(window.exam_key),
                                          window.format.exam)[0],
            start_time = parseInt(new Date().getTime() / 1000, 10),
            end_time = exam_data.end_time,
            length = end_time - start_time,
            time_out_id;
        window.start_watch_action = function () {
            var now_second = parseInt(new Date().getTime() / 1000, 10),
                rest_second = end_time - now_second,
                m = parseInt(rest_second / 60, 10),
                s = rest_second % 60,
                note;
            if (rest_second <= 0) {
                window.view.set.time_rest("0分0秒");
                window.clearTimeout(time_out_id);
                window.loading();
                note = window.confirm("考试时间到\n请交卷！");
                window.listener.submit_answer();
            } else {
                window.view.set.time_rest(m + "分" + s + "秒");
                time_out_id = window.setTimeout(window.start_watch_action, 1000);
            }
        };
        if (exam_data.category_num !== 1 && window.page_his === false) {
            window.start_watch_action();
        }
    },
    "addEventListener": function () {
        "use strict";
        $("#submit_answer").click(window.listener.submit_answer);
        $("#close_paper").click(window.listener.close_paper);
        window.hideLoading();
    }
};
window.init_func_list = ["global_var",
                         "paper_data",
                         "question_data",
                         "addEventListener",
                         "start_watch"];
window.listener = {
    "submit_answer": function () {
        "use strict";
        window.loading();
        var detail = window.format.s2c(window.storage(window.detail_key),
                                       window.format.detail)[0],
            question_list = detail.question,
            index = 0,
            length = question_list.length,
            item,
            answer_dic = {};
        for (index = 0; index < length; index += 1) {
            item = question_list[index];
            answer_dic[item.id] = $('.answer_{id}:checked'.format({
                id: item.id
            })).val() || "";
        }
        $.ajax({
            url:  window.exam_key,
            type: "PUT",
            dataType: "json",
            async: true,
            data: JSON.stringify({answer: answer_dic}),
            success: function (result, status) {
                window.storage(window.exam_key, result.data);
                var paper_data = window.format.s2c(window.storage(window.paper_key),
                                                   window.format.paper)[0];
                window.location.assign("/major/1/history/{category}/".format({
                    id: paper_data.id,
                    category: paper_data.category_num === 1 ? "train" : "paper"
                }));
                window.hideLoading();
            }
        });
    },
    "close_paper": function () {
        "use strict";
        window.close();
    }
};